#!/usr/bin/python3

# SPDX-FileCopyrightText: Red Hat, Inc.
# SPDX-License-Identifier: GPL-2.0-or-later

"""
Push a git branch to remote, modifying the remote working directory.

To use this script, you need to clone vdsm on the host. In this example we
clone in /home/user/src:

    ssh myhost
    cd src
    git clone https://github.com/oVirt/vdsm.git

Add a remote on your developement machine:

    git remote add myhost ssh://user@myhost:/home/user/src/vdsm/.git

With this, you can push the current branch to `myhost` with:

    git-sync myhost

To push another branch use:

    git-sync myhost mybranch

"""

import os
import sys
import uuid
import subprocess
from urllib.parse import urlparse


def run(cmd):
    return subprocess.check_output(cmd).decode().strip()


if len(sys.argv) < 2:
    print("Usage: git-sync REMOTE [BRANCH]")
    sys.exit(2)

remote = sys.argv[1]

if len(sys.argv) > 2:
    branch = sys.argv[2]
else:
    branch = run(["git", "rev-parse", "--abbrev-ref", "HEAD"])

tmp_branch = "tmp-%s" % uuid.uuid4()

# NOTE: this works only with ssh:// URL:
#   ssh://user@host:/home/user/src/vdsm/.git
# I would be nice to support also:
#   user@host:src/vdsm/.git
remote_url = urlparse(run(["git", "remote", "get-url", remote]))

# netloc='user@host1:',
netloc = remote_url.netloc.rstrip(":")

# path='/home/user/vdsm/.git',
path = remote_url.path.replace("/.git", "")

run(["ssh", netloc, f"cd {path} && git checkout -b {tmp_branch}"])

run(["git", "push", "-f", remote, branch])

run(["ssh", netloc, f"cd {path} && git checkout {branch} && git branch -D {tmp_branch}"])
